import { getInfo, getPubKey, login, logout } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    id: '',
    role: '',
    phone: ''
  }
}
const state = getDefaultState()
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  }, SET_TOKEN: (state, token) => {
    state.token = token
  }, SET_NAME: (state, name) => {
    state.name = name
  }, SET_ID: (state, id) => {
    state.id = id
  }, SET_ROLE: (state, role) => {
    state.role = role
  }, SET_PHONE: (state, phone) => {
    state.phone = phone
  }
}
const actions = {
  // 这里在处理登录业务
  login({ commit }, pubUser) {
    return new Promise((resolve, reject) => {
      const { teacherId, password } = pubUser
      login(teacherId, password).then(response => {
        const { tokenValue, tokenName } = response.data
        if (tokenName === 'XAUT') { // 后端设置的tokenName
          commit('SET_TOKEN', tokenValue)
          setToken(tokenValue)
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { name, teacherId, level, phone } = data
        commit('SET_NAME', name)
        commit('SET_ID', teacherId)
        commit('SET_ROLE', level)
        commit('SET_PHONE', phone)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get pubKey
  getPubKey({ commit }, id) {
    return new Promise((resolve, reject) => {
      getPubKey(id).then(response => {
        const { data } = response
        if (!data) {
          alert('GetPubKey failed, please Check Server')
          return reject('GetPubKey failed, please Check Server')
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}
export default {
  namespaced: true, state, mutations, actions
}

